﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace CoachingOrganizer.WinPhone.UITools
{
    public class CommandImpl : ICommand
    {
        private readonly Action _execute;
        private readonly Action<object> _executeWithParameter;
        private readonly Func<bool> _canExecute;
        private readonly Func<object, bool> _canExecuteWithParameter;
        private readonly bool _useAutoRefresh;
        private EventHandler _canExecuteChanged;

        public event EventHandler CanExecuteChanged
        {
            add
            {
                _canExecuteChanged += value;
                //if (_useAutoRefresh)
                //    CommandManager.RequerySuggested += value;
            }
            remove
            {
                _canExecuteChanged -= value;
                //if (_useAutoRefresh)
                //    CommandManager.RequerySuggested -= value;
            }
        }

        public CommandImpl(Action execute, bool useAutoRefresh)
            : this(execute, null, useAutoRefresh)
        {

        }

        public CommandImpl(Action<object> execute, bool useAutoRefresh)
            : this(execute, null, useAutoRefresh)
        {

        }

        public CommandImpl(Action execute, Func<bool> canExecute, bool useAutoRefresh)
        {
            _useAutoRefresh = useAutoRefresh;
            _execute = execute;
            _canExecute = canExecute;
        }

        public CommandImpl(Action<object> execute, Func<object, bool> canExecute, bool useAutoRefresh)
        {
            _useAutoRefresh = useAutoRefresh;
            _executeWithParameter = execute;
            _canExecuteWithParameter = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? _canExecuteWithParameter == null ? true : _canExecuteWithParameter(parameter) : _canExecute();
        }

        public void Execute(object parameter)
        {
            if (_execute != null)
                _execute();
            if (_executeWithParameter != null)
                _executeWithParameter(parameter);
        }

        public void NotifyCanExecuteChanged()
        {
            OnCanExecuteChanged();
        }

        protected virtual void OnCanExecuteChanged()
        {
            EventHandler handler = _canExecuteChanged;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }
    }
}
